import syscall
import strings
import libc

type time_t = struct {
    i64 sec
    i64 nsec
    rawptr<libc.tm> tm
}

fn time_t.timestamp():i64 {
    return self.sec
}

fn time_t.ms_timestamp():i64 {
    return self.sec * 1000 + self.nsec / 1000000
}

fn time_t.ns_timestamp():i64 {
    return self.sec * 1000000000 + self.nsec
}

fn time_t.datetime():string {
    var buf = vec_new<u8>(0, 100)// 必须预留足够大的空间,才能正常引用

   var len = libc.strftime(buf.ref() as libc.cstr, buf.len() as u64, '%Y-%m-%d %H:%M:%S'.to_cstr(), self.tm)
   buf = buf.slice(0, len as i64)

   return buf as string
}

// 将 time_t 使用当前时间进行初始化
fn now():time_t {
    var sys_time = syscall.gettime() catch err {
        return time_t{}
    }

    var t = time_t{
        sec: sys_time.sec,
        nsec: sys_time.nsec,
        tm: libc.localtime(&(sys_time.sec as libc.time_t)),
    }

    return t
}

fn unix():i64 {
    return now().timestamp()
}